<template>
  <view class="reg-container">
    <view class="bg-container" :style="styleBg">
      <b-image :is-asset="true" :need-clip="false" src="/static/images/appdown/reg_bg.png" />
    </view>
    <view class="reg-plane">
      <view class="reg-invite-info">
        <view class="avater">
          <image v-if="inviteInfo.head_img" :src="inviteInfo.head_img" />
          <image v-else src="/static/images/mine/touxiang.png" />
        </view>
        <view class="userinfo">{{ inviteInfo.nickname }} 邀请你加入碧选</view>
      </view>
      <view class="input-container">
        <view class="input-item">
          <view class="country-code" @click="showCountryCode=true">{{ countryCode }}<image src="/static/images/appdown/reg_icon.png" class="down-icon" /></view>
          <input v-model="phoneNumber" type="number" maxlength="11" placeholder="请输入您的手机号码" @blur.prevent="changeBlur" />
          <view v-show="phoneNumber.length > 0" class="close-icon" @click="clearNumber"><b-image width="24" height="24" :is-asset="true" class="icon-close" :need-clip="false" src="/static/images/appdown/icon_close_grey.png" /></view>
        </view>
        <view class="input-item">
          <input v-model="messageCode" type="tel" placeholder="请输入短信验证码" maxlength="6" @blur.prevent="changeBlur" />
          <view class="msg-code" @click="verify">{{ getVerify }}</view>
        </view>
      </view>
      <view class="reg-tip" @click="lookInfo">注册代表同意《碧选用户隐私协议》</view>
      <view class="reg-btn-black" :class="{'btn-gray': !canLogin}" @click="loginto">注册</view>
    </view>
    <view class="reg-down-app" @click="goDownApp('down', 0)">已有账号点此直接下载APP</view>
    <view class="country-list" :class="{'show': showCountryCode}">
      <view class="country-header"><b-image src="/static/images/icon/icon_return_circle.png" width="52" height="52" :is-asset="true" :need-clip="false" class="back-icon" @click="showCountryCode=false" />选择所在的地区</view>
      <view class="country-code-wrapper">
        <view class="country-code-inner">
          <view v-for="(item, index) in regionList" :key="index" class="country-code-item" @click="handleSelectCode(item)">
            <view>{{ item.region }}</view>
            <view>{{ item.region_code }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
// #ifdef H5
import AppUtils from '@/utils/AppUtils'
// #endif
import './index.scss'
export default {
  data() {
    return {
      inviteCode: '',
      phoneNumber: '',
      messageCode: '',
      getVerify: '获取验证码',
      inviteInfo: {},
      countryCode: '+86',
      showCountryCode: false,
      loginBtnName: '注册',
      regionList: [],
      styleBg: ''
    }
  },
  onLoad(options) {
    this.open_id = options.open_id
    this.inviteCode = options.invite_code || options.inviteCode || options.share_code
    this.getInviteInfo()
    this.getCountryCodeDate()
    // #ifdef H5
    AppUtils.ShareTimeline({
      showShare: false
    })
    document.body.style.height = (document.body.clientHeight || document.documentElement.clientHeight) + 'px'
    // #endif
    const res = uni.getSystemInfoSync()
    const height = res.windowHeight + 80 / 750 * res.windowWidth
    this.styleBg = `width: ${height * 750 / 1337}px; height: ${height}px`
  },
  computed: {
    canLogin() {
      return this.messageCode.length === 6 && (/^\d{8,11}$/.test(this.phoneNumber.replace(/\s*/g, '')))
    }
  },
  methods: {
    // 获取验证码
    async verify() {
      if (this.getVerify !== '获取验证码') {
        return
      }
      if (!(/^\d{8,11}$/.test(this.phoneNumber.replace(/\s*/g, '')))) {
        this.mToast('请输入正确的手机号')
      } else {
        this.subcli()
      }
    },
    // 发送短信
    async subcli() {
      const res = await this.$api.loginApi.sendSms(this.countryCode, this.phoneNumber.replace(/\s*/g, ''))
      if (res.code) return
      this.mToast('短信发送成功，请注意查收！')
      this.value = 60
      this.getVerify = this.value + 's'
      var timers = setInterval(() => {
        this.value--
        this.getVerify = this.value + 's'
        if (this.value <= 0) {
          clearInterval(timers)
          this.getVerify = '获取验证码'
        }
      }, 1000)
    },
    // 注册
    async loginto() {
      if (this.loginBtnName !== '注册' || !this.canLogin) {
        return
      }
      this.loginBtnName === '注册...'
      if (!(/^\d{8,11}$/.test(this.phoneNumber.replace(/\s*/g, '')))) {
        this.mToast('请输入正确的手机号')
        this.loginBtnName = '注册'
        return
      }

      if (this.messageCode.length !== 6) {
        this.mToast('短信验证码错误')
        this.loginBtnName = '注册'
        return
      }

      let inviteCode = this.inviteCode
      if (!inviteCode) {
        inviteCode = uni.getStorageSync('share_code')
      }

      var login = {
        region_code: this.countryCode,
        mobile: this.phoneNumber.replace(/\s*/g, ''),
        sms_code: this.messageCode,
        invite_code: inviteCode,
        request_url: '',
        bind_channel: '1' // 1: 通过H5分享邀请码
      }

      if (this.open_id) {
        login.open_id = this.open_id
      }
      console.log(login)
      const res = await this.$api.loginApi.mobileLogin(login)
      if (res.success) {
        if (this.invideCode && res.data.user && !res.data.user.referral_code) {
          let url = ''
          // #ifdef H5
          url = window.location.href
          // #endif
          await this.$api.mineApi.bindInviteCode({
            request_url: url,
            invite_code: inviteCode,
            bind_channel: '1' // 1: 通过H5分享邀请码
          })
          uni.setStorageSync('share_code', '')
        }
        this.$store.dispatch('SET_USER', {
          token: res.data.token,
          userInfo: res.data.user
        })
        this.goDownApp('login', (res.data.is_first_login + ''))
      }
    },
    goDownApp(from, type) {
      this.$navigateTo(`/pagesOther/download/index?from=${from}&isfirst=${type}`)
    },
    lookInfo() {
      this.$navigateTo(`/pagesMine/rule/index?type=userPrivacy`)
    },
    // 获取用户信息
    async getInviteInfo() {
      if (!this.inviteCode) {
        this.inviteCode = uni.getStorageSync('share_code')
      }
      if (!this.inviteCode) return
      const res = await this.$api.mineApi.getInfoByInviteCode(this.inviteCode)
      if (res.data) {
        this.inviteInfo = res.data
      }
      uni.setStorageSync('share_code', this.inviteCode)
    },
    // 获取countyrcode信息
    async getCountryCodeDate() {
      const res = await this.$api.loginApi.getMobileRegion({
        page_size: 100,
        page_no: 1
      })
      this.regionList = res.data
    },
    handleSelectCode(item) {
      this.countryCode = item.region_code
      this.showCountryCode = false
    },
    clearNumber() {
      setTimeout(() => {
        this.phoneNumber = ''
      }, 200)
    },
    changeBlur() {
      // #ifdef H5
      const u = navigator.userAgent
      const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      if (isIOS) {
        setTimeout(() => {
          const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0
          window.scrollTo(0, Math.max(scrollHeight - 1, 0))
        }, 200)
      }
      // #endif
    },
    mToast(msg) {
      uni.showToast({
        title: msg,
        icon: 'none'
      })
    }
  }
}
</script>
